package com.example.demo.config;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.demo.dao.Sys_permissionMapper;
import com.example.demo.dao.SysuserMapper;
import com.example.demo.domain.Role_permission;
import com.example.demo.domain.Sys_permission;
import com.example.demo.domain.Sysrole;
import com.example.demo.domain.Sysuser;
import com.example.demo.services.LoginService;

//实现AuthorizingRealm接口用户用户认证
public class MyShiroRealm extends AuthorizingRealm{
  @Autowired
  private SysuserMapper sysuserMapper;
  @Autowired
  private Sys_permissionMapper sys_permissionMapper;

  //角色权限和对应权限添加
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      //获取登录用户名
      String name= (String) principalCollection.getPrimaryPrincipal();
      //查询用户名称
      Sysuser sysuser = sysuserMapper.findByName(name);
      List<Sys_permission> Sys_permission =  sys_permissionMapper.queryLeftModel(sysuser.getName());
    
      //添加角色和权限
      SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
      for(Sys_permission permission : Sys_permission) {
    	  simpleAuthorizationInfo.addStringPermission(permission.getHref()); 
      }
      return simpleAuthorizationInfo;
  }

  //用户认证
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
      if (authenticationToken.getPrincipal() == null) {
          return null;
      }
      
      //获取用户信息
      String name = authenticationToken.getPrincipal().toString();
      Sysuser sysuser = sysuserMapper.findByName(name);
      if (sysuser == null) {
          //这里返回后会报出对应异常
          return null;
      } else {
          //这里验证authenticationToken和simpleAuthenticationInfo的信息
          SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, sysuser.getPassword().toString(), getName());
          return simpleAuthenticationInfo;
      }
  }
}